package com.lz.autotest.project.websocketApi.netty.handler;

import com.lz.autotest.project.websocketApi.netty.store.ChannelStore;
import com.lz.autotest.project.websocketApi.netty.store.WebSocketSession;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.util.AttributeKey;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;


/**
 * 消息处理,单例启动
 *
 * @author qiding
 */
@Slf4j
@Component
@ChannelHandler.Sharable
@RequiredArgsConstructor
public class MessageHandler extends SimpleChannelInboundHandler<WebSocketFrame> {

    private final WebsocketMessageHandler websocketHandler;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof HttpRequest) {
            HttpRequest mReq = (HttpRequest) msg;
            // 从请求头获取 nginx 反代设置的客户端真实 IP
            String clientIP = mReq.headers().get("X-Real-IP");
            // 如果为空则使用 netty 默认获取的客户端 IP
            if (clientIP == null) {
                InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
                clientIP = insocket.getAddress().getHostAddress();
            }
            if (clientIP.equals("127.0.0.1") || clientIP.equals("0:0:0:0:0:0:0:1")) {
                // 根据网卡取本机配置的IP
                try {
                    clientIP = InetAddress.getLocalHost().getHostAddress();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
            }
            ctx.channel().attr(AttributeKey.valueOf("IP")).set(clientIP);

        }
        // 传递给下一个 handler
        ctx.fireChannelRead(msg);
        if (msg instanceof FullHttpRequest) {
            websocketHandler.handleHttpRequest(ctx, (FullHttpRequest) msg);
            log.debug("\n");
            log.debug("客户端{}握手成功!", ctx.channel().id());
        }
        try {
            super.channelRead(ctx, msg);
        } catch (io.netty.util.IllegalReferenceCountException e) {
            //该异常触发时，netty底层已经做了处理
        }
        ChannelStore.bind(ctx, String.valueOf(ctx.channel().id()));
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
        log.debug("\n");
        log.debug("channelId:" + ctx.channel().id());
        websocketHandler.handleWebSocketFrame(ctx, frame);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        log.debug("\n");
        log.debug("断开连接");
        // 释放缓存
        ChannelStore.closeAndClean(ctx);
        WebSocketSession.clear(ctx.channel().id());
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.debug("\n");
        log.debug("成功建立连接,channelId：{}", ctx.channel().id());
        super.channelActive(ctx);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        log.debug("心跳事件时触发");
    }
}
